/*
 * @Author: Dorange.Wang
 * @Date: 2021-07-07 11:29:24
 * @LastEditors: your name
 * @LastEditTime: 2021-07-20 11:32:18
 * @Description: file content
 */
import storage from "store2";
import { APP_TOKEN, APP_UNIQUE } from "@/utils/const";

const getQueryParameters = () => {
  const url = window.location.href;
  const search = url.split("?")[1];
  if (!search) {
    return {};
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"') +
      '"}'
  );
};

const genQueryString = (obj = {}) => {
  let str = "";
  Object.keys(obj).forEach((key) => {
    str += `${key}=${obj[key]}`;
  });
  return str ? `?${str}` : "";
};

const DEFAULT_UNIQUE = "2r3g5ol";
const DEFAULT_TOKEN = "";

console.log("当前环境：", process.env.NODE_ENV);

const params = getQueryParameters();
const token = (params.token || "").replace("#/", "") || DEFAULT_TOKEN;
const unique = (params.unique || "").replace("#/", "") || DEFAULT_UNIQUE;
token && storage.set(APP_TOKEN, token);
unique && storage.session.set(APP_UNIQUE, unique);

delete params.token;
delete params.unique;
delete params.lang;

const url = window.location.href;
const redirect = url.split("?")[0] + genQueryString(params);
console.log("原始地址：", url);
console.log("重定向地址：", redirect);
url !== redirect && window.location.replace(redirect);
